package com.companyName.common.redis;

import java.util.Set;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

public class JedisClusterFactory extends AbsJedisFactory implements FactoryBean<JedisCluster> ,InitializingBean{
	/**
	 * Jedis集群
	 */
	private JedisCluster jedisCluster;
	
	@Override
	public JedisCluster getObject() throws Exception {
		return jedisCluster;
	}

	@Override
	public Class<?> getObjectType() {
		return (this.jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class);
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if(redisConfig.isCluster()){
			Set<HostAndPort> hostAndPortSet = parseHostAndPort(redisConfig.getAddress());
			GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();

			genericObjectPoolConfig.setMaxWaitMillis(redisConfig.getMaxWaitMillis());
			genericObjectPoolConfig.setMaxTotal(redisConfig.getMaxTotal());
			genericObjectPoolConfig.setMinIdle(redisConfig.getMinIdle());
			genericObjectPoolConfig.setMaxIdle(redisConfig.getMaxIdle());

			jedisCluster = new JedisCluster(hostAndPortSet, redisConfig.getTimeout(), redisConfig.getMaxRedirections(), genericObjectPoolConfig);
		}		
	}
	
}
